package com.lkd.http.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.VMSystem;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.*;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.*;
import com.lkd.service.*;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.lkd.common.UserConstants.ROLE_CODE_ADMIN;

@RestController
@RequestMapping("/task")
public class TaskController extends  BaseController{
    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskTypeService taskTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer producer;

    //1.路径传参  GET http://localhost/user/2/3  参数属于url一部分
    @GetMapping("/user/{id}/{roleCode}")
    public void test1(@PathVariable("id") Long id,@PathVariable("roleCode") Long roleCode){

    }

    //2.query 查询参数 GET http://localhost/user?id=1&&page=1 拼接多个参数使用&&  key value键值对形式
    @GetMapping("/user")
    public void test2(@RequestParam(required = false,defaultValue = "1") Long id,Long page){

    }

    //3.header 请求头，key value 一般用于通用参数，传递token
    @GetMapping("/user2")
    public void test3(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
    }

    //4.form表单 form-data  x-www-form-urlencoded  提交表单，使用form表单enctype不同，
    // 默认x-www-form-urlencoded使用key value封装 ，
    // 如果要使用form-data将enctype= form-data。本质上以key value形式传递，还可以传递文件。
    @GetMapping("/user3")
    public void test4(MultipartFile file){

    }

    //5.json ajax发送请求，请求body中封装json数据，最常用的一种方式 @RequestBody
    //移动、联通、电信 三大运营商 接口 {"HNZZHFCX"}
    @PostMapping("/create")
    public boolean create(@RequestBody TaskViewModel taskViewModel){
        //1.完成创建接口
        Integer assignorId = getUserId();
        if(assignorId == null){
            throw new LogicException("登录用户信息不存在!");
        }
        taskViewModel.setAssignorId(assignorId);
        taskService.create(taskViewModel);
        //2.API POST中进行测试
        return true;
    }

    /**
     * 搜索工单
     * @param pageIndex
     * @param pageSize
     * @param innerCode 设备编号
     * @param userId  工单所属人Id
     * @param taskCode 工单编号
     * @param status 工单状态
     * @param isRepair 是否是维修工单
     * @return
     */
    @GetMapping("/search")
    public Pager<TaskEntity> search(
            @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Long pageIndex,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Long pageSize,
            @RequestParam(value = "innerCode",required = false,defaultValue = "") String innerCode,
            @RequestParam(value = "userId",required = false,defaultValue = "") Integer userId,
            @RequestParam(value = "taskCode",required = false,defaultValue = "") String taskCode,
            @RequestParam(value = "status",required = false,defaultValue = "") Integer status,
            @RequestParam(value = "isRepair",required = false,defaultValue = "") Boolean isRepair,
            @RequestParam(value = "start",required = false,defaultValue = "") String start,
            @RequestParam(value = "end",required = false,defaultValue = "") String end){
        return taskService.search(pageIndex,pageSize,innerCode,userId,taskCode,status,isRepair,start,end);
    }



    /**
     * 根据taskId查询
     * @param taskId
     * @return 实体
     */
    @GetMapping("/taskInfo/{taskId}")
    public TaskEntity findById(@PathVariable Long taskId){
        return taskService.getById(taskId);
    }


    @GetMapping("/allTaskStatus")
    public List<TaskStatusTypeEntity> getAllStatus(){
        return taskService.getAllStatus();
    }

    /**
     * 获取工单类型
     * @return
     */
    @GetMapping("/typeList")
    public List<TaskTypeEntity> getProductionTypeList(){
        return taskTypeService.list();
    }

    /**
     * 获取工单详情
     * @param taskId
     * @return
     */
    @GetMapping("/details/{taskId}")
    public List<TaskDetailsEntity> getDetail(@PathVariable long taskId){
        return taskDetailsService.getByTaskId(taskId);
    }


    @GetMapping("/accept/{taskId}")
    public boolean accept(@PathVariable("taskId") long taskId ){
        TaskEntity task = checkUserId(taskId);
        //判断工单状态不是待处理抛出异常
        if(!Objects.equals(task.getTaskStatus(), VMSystem.TASK_STATUS_CREATE)){
            throw new LogicException("工单状态不是待处理，不能进行工单接受");
        }

        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS); //修改状态为进行中
        taskService.updateById(task);

//        taskService.update(Wrappers.<TaskEntity>lambdaUpdate()
//                .eq(TaskEntity::getTaskId,task.getTaskId())
//                .set(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS)
//        ); // update tb_task set task_status = 2 where task_id = 1000001
        return true;
    }

    private TaskEntity checkUserId(long taskId) {
        Integer userId = getUserId(); //登录用户id
        TaskEntity task = taskService.getById(taskId);
        //判断task对象是否存在
        if(task == null){
            throw new LogicException("工单号不正确!");
        }
        //判断执行ID和登录用户ID是否相同

        //远程调用获取用户角色，判断是否是管理员
        //所有管理员不需要进行身份验证，直接可以操作工单
        UserVO user = userService.getUser(userId);
        if(user == null){
            throw new LogicException("登录用户不存在!");
        }
        String roleCode = user.getRoleCode();

        if (!ROLE_CODE_ADMIN.equals(roleCode)) {
            if (!Objects.equals(task.getUserId(), userId)){
                throw new LogicException("没有权限进行操作!");
            }
        }



        return task;
    }

    @PostMapping("/cancel/{taskId}")
    public boolean cancel(@PathVariable("taskId") long taskId,@RequestBody CancelTaskViewModel model ){
        TaskEntity task = checkUserId(taskId);
        taskService.cancel(task,model);
        return true;
    }

    @GetMapping("/complete/{taskId}")
    public boolean complete(@PathVariable("taskId") long taskId ){
        TaskEntity task = checkUserId(taskId);

        taskService.complete(task);


        return true;
    }


    @GetMapping("/emq")
    public void emq(){
//        TaskCompleteContract contract = new TaskCompleteContract();
//        contract.setInnerCode("100001");
//        contract.setTaskType(1);
//        try {
//            producer.send("server/vms/test",2,contract);
//            //producer.send("testa",2, JsonUtil.serialize(taskEntity));
//        } catch (JsonProcessingException e) {
//            throw new LogicException("emq消息对象转换出错" + e.getMessage());
//        }
        Integer leastTaskCountUser = taskService.getLeastTaskCountUser(1, true);
        System.out.println(leastTaskCountUser);
    }

    /**
     * 将每个人员工单数保存到redis
     */



}